package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.fegin.MemberFeignService;
import com.atguigu.gulimall.auth.fegin.SmsFeginService;
import com.atguigu.gulimall.auth.vo.RegisterVo;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author lk
 * @version 1.0.0
 * @Description LoginController
 * @createTime 2024/1/24 11:25
 */
@Controller
public class LoginController {

    @Autowired
    private SmsFeginService smsFeginService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping(value = "/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        //TODO 接口防刷
        //处理一个手机号码60s内多次获取短信验证码问题
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(StringUtils.isNotEmpty(redisCode)){
            //活动存入redis的时间，用当前时间减去存入redis的时间，判断用户手机号是否在60s内发送验证码
            long currentTime = Long.parseLong(redisCode.split("_")[1]);
            //单位为毫秒，因此，60秒要转化为毫秒60000
            if(System.currentTimeMillis() - currentTime < 60000){
                //60s内不能再发
              return  R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        //2、验证码的再次效验 redis.存key-phone,value-code
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        String codeNum = String.valueOf(code);
        String redisStorage = codeNum + "_" + System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, redisStorage,10, TimeUnit.MINUTES);
        smsFeginService.sendCode(phone,codeNum);
        return R.ok();
    }
    private static String getStringRandom() {
        Random random = new Random();
        //把随机生成的数字转成字符串
        StringBuilder str = new StringBuilder(String.valueOf(random.nextInt(9)));
        for (int i = 0; i < 5; i++) {
            str.append(random.nextInt(9));
        }
        return str.toString();
    }

    @PostMapping(value = "/register")
    public String register(@Valid RegisterVo registerVo, BindingResult result, RedirectAttributes redirectAttributes){
        //1.校验出错，转发到注册页
        if(result.hasErrors()){
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //2、校验验证码
        String code = registerVo.getCode();
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());
        if(StringUtils.isNotEmpty(s)){
            if(code.equals(s.split("_")[0])){
                //删除验证码；令牌机制
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());
                //验证通过。调用远程服务进行注册,将数据存入数据库
                R registResult = memberFeignService.regist(registerVo);
                if(registResult.getCode() == 0){
                    //成功
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    Map<String,String> errors = new HashMap<>();
                    errors.put("msg", registResult.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            } else{
                Map<String,String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            Map<String,String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo){
        //调用远程用户服务
        //成功之后，返回首页
        return "redirect:http://gulimall.com";
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute != null){
            return "redirect:http://gulimall.com";
        } else {
            return "login";
        }
    }

    @GetMapping("/reg.html")
    public String regPage(){
        return "reg";
    }

}
